import { computed, onUnmounted, ref } from "vue"
//时间格式化插件
import dayjs from "dayjs"
//封装倒计数逻辑函数
export const useCountdown = () => {
  //1.响应式的数据
  //定时器
  let timer = null
  const time = ref(0)
  //格式化时间  XX分XX秒
  const fromaTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
  //2.倒计数函数
  const start = (currentTime) => {
    //倒计时的逻辑
    fromaTime.value = currentTime
    timer = setInterval(() => {
      time.value--
    }, 1000)
    //优化，定时器的出现可能会出现内存溢出，为了防止可以在组件销毁时，清除定时器
    onUnmounted(() => {
      timer && clearInterval(timer)
    })
  }
  return { fromaTime, start }
}